package com.wkf.truck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wkf.truck.common.CommonEnum;
import com.wkf.truck.common.R;
import com.wkf.truck.model.Favorite;
import com.wkf.truck.dao.FavoriteDao;
import com.wkf.truck.model.Truck;
import com.wkf.truck.service.FavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkf.truck.service.TruckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lxb
 * @since 2021-02-14
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteDao, Favorite> implements FavoriteService {

    @Autowired
    private TruckService truckService;

    @Resource
    private FavoriteDao favoriteDao;

    @Override
    @Transactional
    public R collectTruck(Long userId, Long truckId, String status) {
        //查询该用户是否已收藏该货车
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("truck_id", truckId);
        Favorite existFavorite = favoriteDao.selectOne(wrapper);

        //未收藏
        if (status.equals("true")) {
            //获取货车信息
            Truck truck = truckService.getOne(new QueryWrapper<Truck>().eq("id", truckId));
            if (truck == null) {
                return R.error("收藏失败");
            }
            if (existFavorite == null) {
                Favorite favorite = new Favorite();
                favorite.setTruckCapacity(truck.getCapacity());
                favorite.setTruckDriver(truck.getDriver());
                favorite.setTruckId(truck.getId());
                favorite.setTruckImg(truck.getImg());
                favorite.setTruckType(truck.getType());
                favorite.setUserId(userId);
                favorite.setStatus(CommonEnum.Favorite.收藏.getCode());
                //保存
                favoriteDao.insert(favorite);
            } else {
                existFavorite.setStatus(CommonEnum.Favorite.收藏.getCode());
                this.saveOrUpdate(existFavorite);
            }
            R r = R.ok("200", "收藏成功");
            r.put("status", true);
            return r;
        }
        //取消收藏
        else {
            existFavorite.setStatus(CommonEnum.Favorite.取消收藏.getCode());
            this.saveOrUpdate(existFavorite);
            R r = R.ok("200", "取消收藏");
            r.put("status", false);
            return r;
        }

    }
}
